import React, { useEffect, useState, Component, useRef } from 'react';
import { fetchSync, request } from '@/utils/request';
import { history } from 'umi';
import { connect, router } from 'dva';

import enUS from 'antd/es/locale/en_US';
import {
    Menu, Switch, Divider, Checkbox, Button, Row, Col, Tooltip, notification, Skeleton, Upload,
    Form, Modal, Select, Tree, Icon, Radio, Table, Tag, Pagination, Input, Space, message, Card, Tabs, Collapse, Image, ConfigProvider
} from 'antd';
import { MailOutlined, AppstoreOutlined, SettingOutlined, AudioOutlined, ReloadOutlined, UserOutlined, PlusOutlined, ArrowRightOutlined, MessageOutlined } from '@ant-design/icons';

import * as echarts from 'echarts';
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import styles from './moments.less';
import * as turf from '@turf/turf';
import { Marker } from 'mapbox-gl';
import Mymenu from './mymenu';
import { getByParam, getUserId, getUserName } from '@/utils/loginAssert';
import moment from 'moment';

let markers = [];
let jiuyuanMarkers = [];

const layout = {
    labelCol: {
        span: 6,
    },
    wrapperCol: {
        span: 4,
    },
};
export default (props) => {
    const [activeItem, setActiveItem] = useState('Home')

    const [map, setMap] = useState(null);
    const [feature, setFeature] = useState({});
    const showmapContainer = useRef(null);
    const echarts1 = useRef(null);
    const echarts2 = useRef(null);
    const echarts3 = useRef(null);
    const echarts4 = useRef(null);
    const echarts5 = useRef(null);
    const echarts6 = useRef(null);
    const echarts7 = useRef(null);
    const [myecharts7, setMyecharts7] = useState(null);
    const echarts8 = useRef(null);
    const commentList = useRef(null);

    const [nowTime, setNowTime] = useState()
    const [selectId, setSelectId] = useState('ID1')
    const [jylObj, setjylObj] = useState({
        qszuida: 158,
        qspinjun: 71
    })

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [fileList, setFileList] = useState([])

    const [users, setUsers] = useState([])

    const [momentsList, setMomentsList] = useState([])

    const [isCommentsModalOpen, setIsCommentsModalOpen] = useState(false);

    const [ currentMoment ,setCurrentMoment] = useState(null)

    //初始函数
    useEffect(async () => {
        let data = await fetchSync('/api/user/findAll')
        setUsers(data.data);

        refreshList()
        return () => {

        }
        // 
    }, [])

    const showModal = () => {
        setIsModalOpen(true);
    };
    
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const handleCommentsCancel  = () => {
        setIsCommentsModalOpen(false);
    };

    const refreshList = () => {
        let userId = getUserId()
        let userName = getUserName()
        let friendIds = getByParam('friendIds') || []
        friendIds.push(userId)
        request('/api/joy/moment/findByUserIds', {
            method: 'POST',
            data: friendIds,
        }).then(res => {
            console.log(res);
            if (res.success) {
                setMomentsList(res.data)
            }
        })
    }

    const onFinish = (values) => {
        console.log('Received values of form:', values);
        const { content, list } = values
        let userId = getUserId()
        let userName = getUserName()

        request('/api/joy/moment/save', {
            method: 'POST',
            data: {
                userId,
                userName,
                content,
                base64Images: list.fileList.map(it => it.thumbUrl)
            }
        }).then(res => {
            console.log(res);
            if (res.success) {
                message.success('publish success！')
                refreshList()
                setIsModalOpen(false);
            }
        })
    };

    // 上传
    const getBase64 = (file) =>
        new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = (error) => reject(error);
        });
    const uploadProps = {
        onRemove: (file) => {
            const index = fileList.indexOf(file);
            const newFileList = fileList.slice();
            newFileList.splice(index, 1);
            setFileList(newFileList);
        },
        beforeUpload: (file) => {
            const isJpgOrPng = true || file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/gif';
            if (!isJpgOrPng) {
                message.error('请上传图片文件 格式 JPG/PNG/JPG/GIF !');
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                message.error('图片大小不超过 2MB!');
            }
            if (isJpgOrPng && isLt2M) {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = e => {
                    file.originFileObj = file
                    file.thumbUrl = e.target.result;
                    let flag = 0;
                    fileList.forEach((item, index) => {
                        if (file.name === item.name) {
                            message.error("文件已存在!");
                            flag = 1;
                        }
                    })
                    if (!flag) {
                        setFileList([...fileList, file])
                    }
                    return false;
                };
            } else {
                return false;
            }
        },
        fileList,
    };
    const handlePreview = async (file) => {
        console.log(file)
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }

        let images = []
        if (file.url) {
            images.push(file.url)
        } else {
            images.push(file.preview)
        }
        // setPreviewImages(images);
        // setPreviewVisible(true);
        // setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
    };
    const uploadButton = (
        <div>
            <PlusOutlined />
            <div
                style={{
                    marginTop: 8,
                }}
            >
                Upload
            </div>
        </div>
    );

    // comments
    const onFinishComments = (values) => {
        let userName = getUserName()
        const { content } = values;
        request('/api/joy/comments/save', {
            method: 'POST',
            data: {
                userName,
                content,
                moment: currentMoment
            }
        }).then(res => {
            console.log(res);
            if (res.success) {
                message.success('success！')
                refreshList()
                setIsCommentsModalOpen(false);
            }
        })
    }
    const toComment = (moment) => {
        setCurrentMoment(moment)
        setIsCommentsModalOpen(true)
    }

    return (
        <div className={styles.container}>
            <div className={styles.top}>
                <img src={require('./img/moments/bk.jpg')} width={'100%'} height={360} />
                <div className={styles.header}>
                    <span>{getUserName()}</span>
                    <img src={ getByParam('avatarImg') || require('./img/head1.png')} width={100}></img>
                </div>
                <div className={styles.btns}>
                    <Button icon={<PlusOutlined />} onClick={showModal} ghost></Button>&nbsp;
                    <Button icon={<ReloadOutlined />} onClick={refreshList} ghost></Button>
                </div>
            </div>

            <div className={styles.bodyContainer}>
                {
                    momentsList.map((moments, index) => {
                        return <div key={index} className={styles.subContainer}>
                            <img src={ 
                                users.find(u=>u.id === moments.userId)?.avatarImg ||
                                require('./img/head1.png')
                            } width={50} height={50}></img>
                            <div className={styles.rightContainer}>
                                <a>{moments.username}</a>
                                <p>{moments.content}</p>
                                {
                                    ( moments.base64Images.length >0 ) &&
                                    <div>
                                        {
                                            moments.base64Images.map((base64 , index)=>{
                                                return <Image key={index} src={base64} width={'33%'}></Image>
                                            })
                                        }
                                    </div>
                                }
                                <div className={styles.btns}>
                                    <span>{moment(moments.momentTime).fromNow()}</span>
                                    <MessageOutlined onClick = { ()=> toComment(moments) }/>
                                </div>

                                {
                                    ( moments.comments.length >0 ) &&
                                    <div className={styles.comments}>
                                        {
                                            moments.comments.map((comment, idx) => {
                                                return <div key={idx} className={styles.item}>
                                                    <a>{comment.userName}</a>
                                                    <p>: {comment.content}</p>
                                                </div>
                                            })
                                        }
                                    </div>
                                }
                            </div>
                        </div>
                    })
                }
            </div>

            <Modal title="Post a moment now" open={isModalOpen} onCancel={handleCancel} footer={null}>
                <Form {...layout} name="nest-messages" onFinish={onFinish}>
                    <Form.Item name="content">
                        <Input.TextArea
                            autoSize={{ minRows: 4, maxRows: 8 }}
                        />
                    </Form.Item>
                    <Form.Item label="" name="list">
                        <Upload
                            listType="picture-card"
                            fileList={fileList}
                            preview={false}
                            headers={{ 'content-type': 'multipart/form-data' }}
                            onPreview={handlePreview}
                            // onPreview={()=>{return false}}
                            // onChange={handleUploadChange}
                            {...uploadProps}
                        >
                            {fileList.length >= 9 ? null : uploadButton}
                        </Upload>
                    </Form.Item>
                    <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 20 }}>
                        <Button type="primary" htmlType="submit">
                            ok
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>

            <Modal title="comments" open={isCommentsModalOpen} onCancel={handleCommentsCancel} footer={null}>
                <Form {...layout} name="nest-messages" onFinish={onFinishComments}>
                    <Form.Item name="content">
                        <Input.TextArea
                            autoSize={{ minRows: 4, maxRows: 8 }}
                        />
                    </Form.Item>
                    <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 20 }}>
                        <Button type="primary" htmlType="submit">
                            ok
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
}
